package com.jy.phonemng.biz.minacodec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class ImageResponseEncoder extends ProtocolEncoderAdapter {

    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out)
                                                                                    throws Exception {
        ImageResponse imageResponse = (ImageResponse) message;
        byte[] imgByte = imageResponse.getImage();
        int flagLen = imageResponse.getFlag().getBytes().length;

        int capacity = (imgByte == null ? 0 : imgByte.length) + flagLen + 8;

        IoBuffer buffer = IoBuffer.allocate(capacity).setAutoExpand(true);
        //put flag;
        buffer.putInt(flagLen);
        buffer.put(imageResponse.getFlag().getBytes());
        //put image;
        buffer.putInt(imgByte == null ? 0 : imgByte.length);
        System.out.println("Buffer left:" + buffer.remaining());
        if (imgByte != null) {
            buffer.put(imgByte);
        }

        buffer.flip();
        out.write(buffer);
    }

    /*private byte[] getBytes(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "PNG", baos);
        return baos.toByteArray();
    }*/
}
